package com.googlecode.continuity.plugin.codecomment.server.service;

import java.util.LinkedList;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.googlecode.continuity.plugin.codecomment.client.CodeComment;
import com.googlecode.continuity.plugin.codecomment.client.CodePointer;

/**
 * CodeCommentServiceHibernate
 *
 * @author Peter Schmitt <aragos@aragos.de>
 */
public class CodeCommentServiceHibernate extends HibernateDaoSupport implements CodeCommentService {

  public List<CodeComment> getCommentsForFile(CodePointer pointer, long firstVersion, long lastVersion) {
    List params = new LinkedList();
    String query = "FROM CodeComment WHERE location.url = ?";
    params.add(pointer.getUrl());

    if (pointer.getFirstLine() > 0) {
      query += " AND location.firstLine >= ?";
      params.add(pointer.getFirstLine());
    }
    if (pointer.getLastLine() > 0) {
      query += " AND location.lastLine <= ?";
      params.add(pointer.getLastLine());
    }
    if (firstVersion >= 0) {
      query += " AND location.version >= ?";
      params.add(firstVersion);
    }
    // for -1 request only latest version
    if (firstVersion == -1) {
      query += " AND location.version = MAX(location.version)";
    } else if (lastVersion >= 0) {
      query += " AND location.version <= ?";
      params.add(lastVersion);
    }

    Object[] par = new Object[params.size()];
    int i = 0;
    for (Object param : params) {
      par[i++] = param;
    }
    return getHibernateTemplate().find(query, par);
  }

  public List<CodeComment> getCommentsForFile(CodePointer pointer) {
    return getCommentsForFile(pointer, pointer.getVersion(), pointer.getVersion());
  }

  public void storeComment(CodeComment comment) {
    getHibernateTemplate().saveOrUpdate(comment);
  }
}
